package com.vast.admin.service;

import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vast.common.core.domain.entity.SysUser;
import com.vast.admin.entity.Placeholder;
import com.vast.admin.entity.PlaceholderTreeDTO;
import com.vast.admin.entity.TempleteRecord;
import com.vast.admin.entity.dto.TemplateFieldsDto;
import com.vast.admin.mapper.PlaceholderMapper;
import com.vast.admin.utils.PlaceholderResolver;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

@Service
@Slf4j
public class PlaceholderService extends ServiceImpl<PlaceholderMapper, Placeholder> {

    @Autowired
    private TempleteRecordService templeteRecordService;

    /**
     * 获取合同参数信息
     * @param templeteRecordId
     * @return
     */
    public List<Map<String, Object>> getPlaceholderByTempleteRecordId(Long templeteRecordId) {
        TempleteRecord templeteRecord = templeteRecordService.getById(templeteRecordId);
        String[] placeholderSortArr = null;
        if (StringUtils.hasText(templeteRecord.getPlaceholderSort())) {
            placeholderSortArr = templeteRecord.getPlaceholderSort().split(",");
        }
        Map<String, List<Placeholder>> map = getPlaceholderByPlaceBelong(templeteRecordId);
        List<Map<String, Object>> result = new LinkedList<>();
        int index = 0;
        for (Map.Entry<String, List<Placeholder>> entry : map.entrySet()) {
            Map<String, Object> tmp = new HashedMap();
            index++;
            tmp.put("index",index); // 便于索引数据显示位置
            tmp.put("label", entry.getKey());
            tmp.put("tips", ""); //选择客户后后提示使用
            tmp.put("templateRecordId", templeteRecordId);
            if (placeholderSortArr != null) {
                int i = getIndex(placeholderSortArr, entry.getKey());
                if (i == -1) {
                    tmp.put("sort", index); //排序值,用于app端表单顺序
                } else {
                    tmp.put("sort", i); //排序值,用于app端表单顺序
                }
            } else {
                tmp.put("sort", index); //排序值,用于app端表单顺序
            }
            tmp.put("items", entry.getValue());
            if (isContains(templeteRecord.getCompanyPart(), entry.getKey())) {
                tmp.put("type", 1);
            } else if (isContains(templeteRecord.getCustomerPart(), entry.getKey())) {
                tmp.put("type", 2);
            } else if (isContains(templeteRecord.getThirdPart(), entry.getKey())) {
                tmp.put("type", 3);
            } else {
                tmp.put("type", 0);
            }
            result.add(tmp);
        }
        //根据sort排序
        Collections.sort(result, new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                if ((int)o1.get("sort") - (int)o2.get("sort") > 0) { //变成 < 可以变成递减排序
                    return 0;
                } else {
                    return -1;
                }
            }
        });
        return result;
    }

    private int getIndex(String[] strArr, String str) {
        if (strArr == null || strArr.length == 0 || StringUtils.isEmpty(str)) {
            return -1;
        }
        int index = 0;
        for (String tmp : strArr) {
            if (str.equals(tmp)) {
                return index;
            }
            index ++;
        }
        return -1;
    }

    /**
     * 是否包含
     * @param part
     * @param str
     * @return
     */
    public boolean isContains(String part, String str) {
        if (StringUtils.hasText(part) && ("," + part + ",").contains("," + str + ",")) {
            return true;
        }
        return false;
    }

    /**
     * 解析表单提交参数
     * @param templeteRecordId
     * @param params
     * @return
     */
    public Map<String, Object> resolverParam(Long templeteRecordId, Map<String, String> params) {
        Map<String, List<Placeholder>> map = getPlaceholderByPlaceBelong(templeteRecordId);
        Map<String, Object> result = new LinkedHashMap<>();
        Map<String, Object> placeholderTagMap = new LinkedHashMap<>();
        for (Map.Entry<String, List<Placeholder>> entry : map.entrySet()) {
            String placeholderBelong = entry.getKey();
            if ("其他".equals(placeholderBelong)) {
                for (Placeholder placeholder : entry.getValue()) {
                    String value = params.get(placeholder.getPlaceholderKey());
                    if (value == null) {
                        value = "";
                    }
                    checkPlaceholder(placeholder, value);
                    result.put(placeholder.getPlaceholderName(), value);
                    getDataByPlaceholderTag(placeholderTagMap, placeholder.getPlaceholderTag(), value);
                }
            } else {
                Map<String, String> belongMap = new LinkedHashMap<>();
                for (Placeholder placeholder : entry.getValue()) {
                    String value = params.get(placeholder.getPlaceholderKey());
                    if (value == null) {
                        value = "";
                    }
                    checkPlaceholder(placeholder, value);
                    belongMap.put(placeholder.getPlaceholderName(), value);
                    getDataByPlaceholderTag(placeholderTagMap, placeholder.getPlaceholderTag(), value);
                }
                result.put(placeholderBelong, belongMap);
            }
        }
        return result;
    }

    /**
     * 获取合同模板对应的参数信息
     * @param templeteRecordId
     * @return
     */
    public List<Placeholder> getPlaceholder(Long templeteRecordId) {
        QueryWrapper<Placeholder> placeholderQueryWrapper = new QueryWrapper<>();
        placeholderQueryWrapper.eq(Placeholder.COL_TEMPLETE_RECORD_ID, templeteRecordId);
        return super.list(placeholderQueryWrapper);
    }

    /**
     * 按分类获取合同模板参数信息
     * @param templeteRecordId
     * @return
     */
    private Map<String, List<Placeholder>> getPlaceholderByPlaceBelong(Long templeteRecordId) {
        List<Placeholder> placeholders = getPlaceholder(templeteRecordId);
        Map<String, List<Placeholder>> map = new HashedMap();
        if (placeholders != null && placeholders.size() > 0) {
            for (Placeholder placeholder : placeholders) {
                String placeholderBelong = placeholder.getPlaceholderBelong();
                if (map.containsKey(placeholderBelong)) {
                    map.get(placeholderBelong).add(placeholder);
                } else {
                    map.put(placeholderBelong, new ArrayList<Placeholder>(){{add(placeholder);}});
                }
            }
        }
        return map;
    }

    /**
     * 处理打标签的特殊字段
     * @param result
     * @param placeholderTag
     * @param value
     */
    private void getDataByPlaceholderTag(Map<String, Object> result, Integer placeholderTag, String value) {

    }

    /**
     * 校验参数
     * @param placeholder
     * @param value
     */
    private void checkPlaceholder(Placeholder placeholder, String value) {

    }


    /**
     * 保存模板配置项
     * @param templateFieldsDtos
     */
    public void saveTemplateFields(SysUser manager, List<TemplateFieldsDto> templateFieldsDtos) {
        if(!templateFieldsDtos.isEmpty()){
            for (TemplateFieldsDto templateFieldsDto : templateFieldsDtos) {
                 List<Placeholder> placeholders = templateFieldsDto.getItems();
                 if(placeholders != null && !placeholders.isEmpty()){
                     for (Placeholder placeholder : placeholders) {
                         placeholder.setUpdateBy(manager.getUserId());
                         placeholder.setUpdateTime(DateTime.now());
                         placeholder.setValid(1);
                         baseMapper.updateById(placeholder);
                     }
                 }
            }
        }

    }

    /**
     * 按类型获取
     * @param templeteRecordId
     * @param tag
     * @return
     */
    public Placeholder getPlaceholderByTag(Long templeteRecordId, Integer tag) {
        QueryWrapper<Placeholder> placeholderQueryWrapper = new QueryWrapper<>();
        placeholderQueryWrapper.eq(Placeholder.COL_TEMPLETE_RECORD_ID, templeteRecordId)
                .eq(Placeholder.COL_PLACEHOLDER_TAG, tag);
        List<Placeholder> placeholders = super.list(placeholderQueryWrapper);
        if (placeholders != null && !placeholders.isEmpty()) {
            return placeholders.get(0);
        } else {
            return null;
        }
    }

    /**
     * 按名称获取
     * @param templeteRecordId
     * @param placeholderName
     * @return
     */
    public Placeholder getPlaceholderByName(Long templeteRecordId, String placeholderName) {
        QueryWrapper<Placeholder> placeholderQueryWrapper = new QueryWrapper<>();
        placeholderQueryWrapper.eq(Placeholder.COL_TEMPLETE_RECORD_ID, templeteRecordId)
                .eq(Placeholder.COL_PLACEHOLDER_NAME, placeholderName);
        List<Placeholder> placeholders = super.list(placeholderQueryWrapper);
        if (placeholders != null && !placeholders.isEmpty()) {
            return placeholders.get(0);
        } else {
            return null;
        }
    }

    /**
     * 获取合同参数中的标记值
     * @param contractParam
     * @param templeteRecordId
     * @param tag
     * @return
     */
    public String getValueByTag(String contractParam, Long templeteRecordId, Integer tag) {
        Placeholder placeholder = getPlaceholderByTag(templeteRecordId, tag);
        if (placeholder == null) {
            return null;
        }
        JSONObject jsonObject = JSON.parseObject(contractParam);
        String result = null;
        if ("其他".equals(placeholder.getPlaceholderBelong())) {
            result = jsonObject.getString(placeholder.getPlaceholderName());
        } else {
            result = jsonObject.getJSONObject(placeholder.getPlaceholderBelong()).getString(placeholder.getPlaceholderName());
        }
        return result;
    }

    /**
     * 获取占位符树结构
     * @param templeteRecordId
     * @return
     */
    public List<PlaceholderTreeDTO> getPlaceholderTree(Long templeteRecordId) {
        QueryWrapper<Placeholder> placeholderQueryWrapper = new QueryWrapper<>();
        placeholderQueryWrapper.eq(Placeholder.COL_TEMPLETE_RECORD_ID, templeteRecordId)
                .ne(Placeholder.COL_PLACEHOLDER_TAG, 5)
                .ne(Placeholder.COL_PLACEHOLDER_NAME, PlaceholderResolver.REPAYMENT_PLAN_FIELD)
                .ne(Placeholder.COL_PLACEHOLDER_NAME, PlaceholderResolver.CONTRACT_NO_FIELD);
        List<Placeholder> placeholders = super.list(placeholderQueryWrapper);
        Map<String, PlaceholderTreeDTO> placeholderTreeDTOMap = new HashMap<>();
        placeholders.stream().forEach(placeholder -> {
            PlaceholderTreeDTO belongPlaceholderTreeDTO;
            if (!placeholderTreeDTOMap.containsKey(placeholder.getPlaceholderBelong())) {
                belongPlaceholderTreeDTO = new PlaceholderTreeDTO();
                belongPlaceholderTreeDTO.setPlaceholderName(placeholder.getPlaceholderBelong());
                belongPlaceholderTreeDTO.setChildren(new ArrayList<>());
                placeholderTreeDTOMap.put(belongPlaceholderTreeDTO.getPlaceholderName(), belongPlaceholderTreeDTO);
            } else {
                belongPlaceholderTreeDTO = placeholderTreeDTOMap.get(placeholder.getPlaceholderBelong());
            }
            PlaceholderTreeDTO placeholderTreeDTO = new PlaceholderTreeDTO();
            placeholderTreeDTO.setId(placeholder.getId());
            placeholderTreeDTO.setPlaceholderName(placeholder.getPlaceholderName());
            belongPlaceholderTreeDTO.getChildren().add(placeholderTreeDTO);
        });
        List<PlaceholderTreeDTO> placeholderTreeDTOS = new ArrayList<>(placeholderTreeDTOMap.size());
        placeholderTreeDTOMap.forEach((s, placeholderTreeDTO) -> placeholderTreeDTOS.add(placeholderTreeDTO));
        return placeholderTreeDTOS;
    }

    /**
     * 通过归属查询占位符
     * @param templateRecordId
     * @param belong
     * @return
     */
    public List<Placeholder> getPlaceholderByBelong(Long templateRecordId, String belong) {
        QueryWrapper<Placeholder> placeholderQueryWrapper = new QueryWrapper<>();
        placeholderQueryWrapper.eq(Placeholder.COL_TEMPLETE_RECORD_ID, templateRecordId)
                .eq(Placeholder.COL_PLACEHOLDER_BELONG, belong);
        return super.list(placeholderQueryWrapper);
    }

}
